package com.lmb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lmb.bean.R;
import com.lmb.bean.User;
import com.lmb.service.UserService;
import com.lmb.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @projectName: reggie
 * @package: com.lmb.controller
 * @className: UserController
 * @author: Eric
 * @description: TODO
 * @date: 2022/9/21 17:01
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        System.out.println(user.getPhone());
        Integer integer = new ValidateCodeUtils().generateValidateCode(4);
        System.out.println(integer);
        session.setAttribute(user.getPhone(), integer);

        return R.success(integer);
    }


    @PostMapping("/login")
    public R login(@RequestBody Map<String,Object> map,HttpSession session){
        System.out.println(map);

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        Object attribute = session.getAttribute(phone);


        if (attribute==null) {
            throw new ClassCastException("验证码过期！！！");
        }

        if(!attribute.toString().equalsIgnoreCase(code)){
            return R.error("验证码输入有误！");
        }

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,phone);
        User one = userService.getOne(userLambdaQueryWrapper);

        if (one == null) {
            one = new User();
            one.setName("u_"+phone);
            one.setPhone(phone);
            userService.save(one);
        }

        session.setAttribute("user",one.getId());
        return R.success(one);
    }

    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功！！！");
    }
}
